package com.cw.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.method.CommonMethod;
import com.cw.dto.*;
import com.cw.entity.*;
import com.cw.mapper2.VYqBrdjxxMapper;
import com.cw.mapper3.LJysqdxxMapper;
import com.cw.mapper3.LJysqdxxXmmxMapper;
import com.cw.request.VYqBrdjxxConditionRequest;
import com.cw.service.*;
import com.cw.util.*;
import com.cw.vo.PatientInfoToDoctorVO;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 查询患者列表信息
 *
 * @author ly
 * @since 2021-08-18
 */
@Service
public class IVYqBrdjxxServiceImpl extends ServiceImpl<VYqBrdjxxMapper, VYqBrdjxx> implements IVYqBrdjxxService {

    @Autowired
    private IExamineSpecialService examineSpecialService;

    @Autowired
    private ILJysqdxxService ilJysqdxxService;

    @Autowired
    private ILJysqdxxXmmxService ilJysqdxxXmmxService;

    @Autowired
    private ILJytmxxService ilJytmxxService;

    @Autowired
    private IExamineSpecialService iExamineSpecialService;

    @Autowired
    private IYqBeizhuService iYqBeizhuService;

    @Autowired
    private LJysqdxxMapper lJysqdxxMapper;

    @Autowired
    private LJysqdxxXmmxMapper lJysqdxxXmmxMapper;

    /**
     * 院前准备列表
     *
     * @param condition 查询条件
     * @return com.github.pagehelper.PageInfo<com.cw.entity.VYqBrdjxx>
     * @author ly
     * @since 2021-08-18 11:02
     */
    @Override
    public PageInfo<VYqBrdjxx> getVYqBrdjxxPagesInfo(VYqBrdjxxCondition condition) {
        List<VYqBrdjxx> resultList = baseMapper.getVYqBrdjxxs(condition);
        resultList.stream()
                .filter(t -> t.getMedicalInsuranceFlag() != null && 0 == t.getMedicalInsuranceFlag())
                .map(t -> t.setYblx("异地医保"))
                .collect(Collectors.toList());
        resultList.stream()
                .filter(t -> t.getMedicalInsuranceFlag() != null && 1 == t.getMedicalInsuranceFlag())
                .map(t -> t.setYblx("苏州医保"))
                .collect(Collectors.toList());
        return PageHelperTool.excutePageInfo(resultList, condition.getPageNum(), condition.getPageSize());
    }

    @Override
    public PageInfo<VRJSZ> getVYqBrdjxxRJSSPagesInfo(VYqBrdjxxCondition condition) {
        List<VRJSZ> resultList = baseMapper.getVYqBrdjxxsRJSS(condition);
        return PageHelperTool.excutePageInfo(resultList, condition.getPageNum(), condition.getPageSize());
    }

    @Override
    public void getVYqBrdjxxDownLoad(VYqBrdjxxCondition condition) {
        try {

            List<YqBeizhu> beizhuList = iYqBeizhuService.getYQBeiZhuList(null);
            List<VYqBrdjxx> sourceList = baseMapper.getVYqBrdjxxs(condition);
            List<VYqBrdjxxYQZB> reportList = new ArrayList<>();
            sourceList.forEach(item -> {
                VYqBrdjxxYQZB newInfo = new VYqBrdjxxYQZB();

                newInfo.setName(item.getName());
                if (item.getSex().equals("2")) {
                    newInfo.setSex("女");
                } else {
                    newInfo.setSex("男");
                }

                newInfo.setAge(item.getAge());
                newInfo.setDeptName(item.getDeptName());
                newInfo.setYblx(item.getYblx());
                newInfo.setRyzt(item.getRyzt());
                newInfo.setEmplName(item.getEmplName());
                newInfo.setYysj(item.getYysj());
                newInfo.setCreateTime(item.getCreateTime());
                newInfo.setRyrq(item.getRyrq());
                newInfo.setClinicCode(item.getClinicCode());
                newInfo.setSpeedProgress(String.join("/", item.getDoit(), item.getTotal()));
                newInfo.setState(item.getState());
                if (item.getState().equals("1")) {
                    newInfo.setState("已登记");
                } else {
                    newInfo.setState("未登记");
                }
                //备注跟预约表取配preid  然后插入
                YqBeizhu match = beizhuList.stream()
                        .filter(t -> t.getPreid().compareTo(item.getPreid()) == 0)
                        .findFirst()
                        .orElse(null);
                if (match != null) {
                    newInfo.setBeizhu(match.getBeizhu());
                }

                reportList.add(newInfo);
            });

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置背景颜色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            //设置头字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 10);
            headWriteFont.setBold(true);
            headWriteCellStyle.setWriteFont(headWriteFont);
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle,
                    contentWriteCellStyle);

            ServletRequestAttributes servletRequestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            String name = String.valueOf(System.currentTimeMillis());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");

            // 根据用户传入字段  set是删除字段
            Set<String> excludeColumnFiledNames = new HashSet<String>();
            excludeColumnFiledNames.add("doit");
            excludeColumnFiledNames.add("total");
            Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(reportList);
            EasyExcel.write(response.getOutputStream(), VYqBrdjxxYQZB.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(new BizMergeStrategy(map))
                    .excludeColumnFiledNames(excludeColumnFiledNames)
                    .sheet("sheet")
                    .doWrite(reportList);
        } catch (Exception ex) {
            int a = 1;
        }

    }

    @Override
//    public void getVYqBrdjxxRJSSDownLoad(VYqBrdjxxCondition condition) {
//        try {
//            List<VRJSZ> sourceList = baseMapper.getVYqBrdjxxsRJSS(condition);
//            sourceList.forEach(item -> {
//                if (item.getSex().equals("2")) {
//                    item.setSex("女");
//                } else {
//                    item.setSex("男");
//                }
//                if(item.getBedType().equals("1"))
//                {
//                    item.setBedType("日间手术");
//                }
//                else
//                {
//                    item.setBedType("日间输注");
//                }
//            });
//
//            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//            //设置背景颜色
//            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
//            //设置头字体
//            WriteFont headWriteFont = new WriteFont();
//            headWriteFont.setFontHeightInPoints((short)10);
//            headWriteFont.setBold(true);
//            headWriteCellStyle.setWriteFont(headWriteFont);
//            //设置头居中
//            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//
//            //内容策略
//            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//            //设置 水平居中
//            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy
//            (headWriteCellStyle, contentWriteCellStyle);
//
//            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
//            .getRequestAttributes();
//            HttpServletResponse response = servletRequestAttributes.getResponse();
//            String name = String.valueOf(System.currentTimeMillis());
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//            String fileName = URLEncoder.encode(name, "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
//
//            // 根据用户传入字段  set是删除字段
//            Set<String> excludeColumnFiledNames = new HashSet<String>();
//            excludeColumnFiledNames.add("Id");
//            excludeColumnFiledNames.add("preid");
//            excludeColumnFiledNames.add("deptName");
//            excludeColumnFiledNames.add("yblx");
//            excludeColumnFiledNames.add("createTime");
//            excludeColumnFiledNames.add("clinicCode");
//            excludeColumnFiledNames.add("medicalInsuranceFlag");
//            excludeColumnFiledNames.add("bedNo");
//            excludeColumnFiledNames.add("doit");
//            excludeColumnFiledNames.add("total");
//            Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(sourceList);
//            EasyExcel.write(response.getOutputStream(), VRJSZ.class)
//                    .registerWriteHandler(horizontalCellStyleStrategy)
//                    .registerWriteHandler(new BizMergeStrategy(map)).excludeColumnFiledNames
//                    (excludeColumnFiledNames).sheet("sheet").doWrite(sourceList);
//        } catch (Exception ex) {
//            int a = 1;
//        }
//
//    }


    /**
     * 院前准备人数统计  已登记/未登记
     *
     * @author xnd
     * 2021 09/29
     */

    public String gePpeopleStatistics(VYqBrdjxxCondition condition) {
        List<VYqBrdjxx> StatisticalResults = new ArrayList<>();
        StatisticalResults = (List<VYqBrdjxx>) baseMapper.getYqYuYueAllPeople(condition);
        //拿到已登记的人数
        List<VYqBrdjxx> registered = StatisticalResults.stream()
                .filter(t -> t.getState().equals("1"))
                .collect(Collectors.toList());
        //拿到未登记的人数
        List<VYqBrdjxx> unregistered = StatisticalResults.stream()
                .filter(t -> t.getState().equals("0"))
                .collect(Collectors.toList());
        //获得已登记人数的长度
        String reglength = String.valueOf(registered.size());
        //获得未登记人数的长度
        String unreglength = String.valueOf(unregistered.size());
        String total = String.valueOf(StatisticalResults.size());
        //把它变成  例：10/20的格式
        String join = String.join("/", reglength, unreglength, total);

        return join;
    }

    /**
     * 院前准备详情
     *
     * @param condition 查询条件
     * @return com.cw.dto.VYqBrdjxxVeiwDTO
     * @author ly
     * @since 2021-08-18 15:36
     */
    @Override
    public VYqBrdjxxVeiwDTO getVYqBrdjxx(VyqBrdjxxVeiwCondition condition) {
        //检验组套集合
        List<String> doctrequestnos = new ArrayList<>();
        //要检验项目集合
        List<String> ZIDComboList = new ArrayList<>();
        VYqBrdjxxVeiwDTO vYqBrdjxxVeiwDTO = new VYqBrdjxxVeiwDTO();
        //基本信息
        VYqBrdjxx vYqBrdjxx = baseMapper.getVYqBrdjxx(condition.getPreid());
        vYqBrdjxxVeiwDTO.setVYqBrdjxx(vYqBrdjxx);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String yysj = vYqBrdjxx.getYysj();
            if (StringUtil.isNotEmpty(yysj)) {
                vYqBrdjxx.setYysj(simpleDateFormat.format(simpleDateFormat.parse(yysj)));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //处方号
        String clinicCode = vYqBrdjxx.getClinicCode();

        //检验明细列表
        vYqBrdjxxVeiwDTO.setLJysqdxxes(ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode));
        List<LJysqdxx> LJysqdxxList = vYqBrdjxxVeiwDTO.getLJysqdxxes();

        if (!CollectionUtil.isEmpty(LJysqdxxList)) {
            for (LJysqdxx item : LJysqdxxList) {
                List<String> doctrequestnoList = new ArrayList<>();
                doctrequestnoList.add(item.getDoctrequestno());
//                根据门诊号去查患者要做的那些检验组套
                List<LJytmxx> listFinish = ilJytmxxService.getExaminaimCodeByDoctrequestno(doctrequestnoList);
//                Examinaimcode就是后面的ZTID,这里是拿到她做完的ZTID
                List<String> ZIDFinishList = listFinish.stream()
                        .map(LJytmxx::getExaminaimcode)
                        .distinct()
                        .collect(Collectors.toList());
//                查询DOCTREQUESTNO这个检验单号,跟每个检验项目的ZTID,还有PATIENTID门诊号
                List<LJysqdxxXmmx> list = ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos(item.getDoctrequestno());
//                这里拿出所有要做的检验项目的ZTID
                ZIDComboList = list.stream().map(t -> t.getZtid().toString()).distinct().collect(Collectors.toList());
//                这里有特殊处理,因为数据库里EXAMINAIMCODE这个字段,就是它的ZTID会有例如“9790^11232^”这种三角符号的出现，要对它进行分割，才能去判断对比
                String strZIDFinish = String.join("", ZIDFinishList);
                List<String> splitZIDFinishList = Arrays.asList(strZIDFinish.split("\\^"));//这里有检验项合并的情况,所以增加了此操作
                String doProcess = "0";
                if (!"".equals(splitZIDFinishList.get(0))) {
                    doProcess = String.valueOf(splitZIDFinishList.size());
                }

                item.setJyProcess(String.join("/", doProcess, String.valueOf(ZIDComboList.size())));
                //比较处理,如果它做了,那么ZTID是可以对应上的，那就是true，如果对应不上就是false
                boolean isTrue = true;
                for (String citem : ZIDComboList) {
                    if (!strZIDFinish.contains(citem)) {
                        isTrue = false;
                        break;
                    }
                }
//               对上的打钩
                item.setJyPass(isTrue);
            }
        }


        //检查报告列表
//          SELECT *FROM  ER_APPLY_OUT
//	WHERE BRMZH = '0005582427'   要检查项目的退费跟缴费的状态就去查这段SQL, BRMZH是患者门诊号
        vYqBrdjxxVeiwDTO.setErApplyOuts(vYqBrdjxx.getErApplyOuts());

        String idenno = vYqBrdjxx.getIdenno();
        //塞入历史状态信息
        if (StringUtil.isNotEmpty(idenno)) {
            vYqBrdjxxVeiwDTO.setHistoryState(getHistoryState(idenno));
        }

        return vYqBrdjxxVeiwDTO;
    }

    @Override
    public VYqBrdjxxVeiwDTO getRJSSVYqBrdjxx(VyqBrdjxxVeiwCondition condition) {


        //检验组套集合
        List<String> doctrequestnos = new ArrayList<>();
        //要检验项目集合
        List<String> ZIDComboList = new ArrayList<>();
        VYqBrdjxxVeiwDTO vYqBrdjxxVeiwDTO = new VYqBrdjxxVeiwDTO();
        //基本信息
        VYqBrdjxx vYqBrdjxx = baseMapper.getRJSSVYqBrdjxx(condition.getPreid());

        vYqBrdjxxVeiwDTO.setVYqBrdjxx(vYqBrdjxx);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String yysj = vYqBrdjxx.getYysj();
            if (StringUtil.isNotEmpty(yysj)) {
                vYqBrdjxx.setYysj(simpleDateFormat.format(simpleDateFormat.parse(yysj)));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //处方号
        String clinicCode = vYqBrdjxx.getClinicCode();

        //检验明细列表
        vYqBrdjxxVeiwDTO.setLJysqdxxes(ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode));
        List<LJysqdxx> LJysqdxxList = vYqBrdjxxVeiwDTO.getLJysqdxxes();

        if (!CollectionUtil.isEmpty(LJysqdxxList)) {
            for (LJysqdxx item : LJysqdxxList) {
                List<String> doctrequestnoList = new ArrayList<>();
                doctrequestnoList.add(item.getDoctrequestno());
//                根据门诊号去查患者要做的那些检验组套
                List<LJytmxx> listFinish = ilJytmxxService.getExaminaimCodeByDoctrequestno(doctrequestnoList);
//                Examinaimcode就是后面的ZTID,这里是拿到她做完的ZTID
                List<String> ZIDFinishList = listFinish.stream()
                        .map(t -> t.getExaminaimcode())
                        .distinct()
                        .collect(Collectors.toList());
//                查询DOCTREQUESTNO这个检验单号,跟每个检验项目的ZTID,还有PATIENTID门诊号
                List<LJysqdxxXmmx> list = ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos(item.getDoctrequestno());
//                这里拿出所有要做的检验项目的ZTID
                ZIDComboList = list.stream().map(t -> t.getZtid().toString()).distinct().collect(Collectors.toList());
//                这里有特殊处理,因为数据库里EXAMINAIMCODE这个字段,就是它的ZTID会有例如“9790^11232^”这种三角符号的出现，要对它进行分割，才能去判断对比
                String strZIDFinish = String.join("", ZIDFinishList);
                List<String> splitZIDFinishList = Arrays.asList(strZIDFinish.split("\\^"));//这里有检验项合并的情况,所以增加了此操作
                String doProcess = "0";
                if (!splitZIDFinishList.get(0).equals("")) {
                    doProcess = String.valueOf(splitZIDFinishList.size());
                }

                item.setJyProcess(String.join("/", doProcess, String.valueOf(ZIDComboList.size())));
                //比较处理,如果它做了,那么ZTID是可以对应上的，那就是true，如果对应不上就是false
                boolean isTrue = true;
                for (String citem : ZIDComboList) {
                    if (!strZIDFinish.contains(citem)) {
                        isTrue = false;
                        break;
                    }
                }
//               对上的打钩
                item.setJyPass(isTrue);
            }
        }


        //检查报告列表
//          SELECT *FROM  ER_APPLY_OUT
//	WHERE BRMZH = '0005582427'   要检查项目的退费跟缴费的状态就去查这段SQL, BRMZH是患者门诊号
        vYqBrdjxxVeiwDTO.setErApplyOuts(vYqBrdjxx.getErApplyOuts());

        String idenno = vYqBrdjxx.getIdenno();
        //塞入历史状态信息
        if (StringUtil.isNotEmpty(idenno)) {
            vYqBrdjxxVeiwDTO.setHistoryState(getHistoryState(idenno));
        }

        return vYqBrdjxxVeiwDTO;
    }


    /**
     * 通过他的身份证去查询他的历史 入院 出院 预约 记录
     *
     * @param idenNo 身份证号
     * @return java.util.List<com.cw.entity.VYqBrdjxx>
     */
    private List<VYqBrdjxx> getHistoryState(String idenNo) {

        LambdaQueryWrapper<VYqBrdjxx> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VYqBrdjxx::getIdenno, idenNo);
        lambdaQueryWrapper.select(VYqBrdjxx::getYyrq, VYqBrdjxx::getCyrq, VYqBrdjxx::getRyrq, VYqBrdjxx::getQxsj);
        lambdaQueryWrapper.orderByDesc(VYqBrdjxx::getYyrq);
        return list(lambdaQueryWrapper);
    }

    /**
     * 院前准备中心报表信息
     *
     * @return java.util.List<com.cw.dto.ReportReadyDocNameDTO>
     * @author ly
     * @since 2021-08-25 15:15
     */
    @Override
    public List<ReportReadyDocNameDTO> getReportList(VYqBrdjxxConditionRequest requestInfo) {

        List<ReportReadyDocNameDTO> reportReadyDocNames = new ArrayList<>();
        try {
            List<ReportReadyDocNameDTO> filterdeptcode = new ArrayList<>();
            reportReadyDocNames = baseMapper.getReportList(requestInfo);
            if (!CollectionUtil.isEmpty(requestInfo.getDeptCodeList())) {
                filterdeptcode = reportReadyDocNames.stream()
                        .filter(t -> requestInfo.getDeptCodeList().contains(t.getDeptCode()))
                        .collect(Collectors.toList());
                if (CollectionUtil.isEmpty(filterdeptcode)) {
                    return null;
                }
            } else {
                filterdeptcode = reportReadyDocNames;
            }
            List<String> clinicCodeList = reportReadyDocNames.stream()
                    .map(ReportReadyDocNameDTO::getClinicCode)
                    .collect(Collectors.toList());
            // 获取相应的诊断号的LJysqdxx集合
            
            LambdaQueryWrapper<LJysqdxx> lJysqdxxQueryWrapper = new LambdaQueryWrapper<>();
            lJysqdxxQueryWrapper.in(LJysqdxx::getPatientno, clinicCodeList);
            List<LJysqdxx> lJysqdxxList = lJysqdxxMapper.selectList(lJysqdxxQueryWrapper);
//            List<LJysqdxx> lJysqdxxList = lJysqdxxMapper.listJyxqdxx(clinicCodeList);
            // 获取lJysqdxxList中所有的doctrequestno形成集合
            List<String> doctRequestNoList = lJysqdxxList.stream()
                    .map(LJysqdxx::getDoctrequestno)
                    .collect(Collectors.toList());
            // 获取另一个比对列表，提前放到jvm内存
            LambdaQueryWrapper<LJytmxx> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(LJytmxx::getExaminaim,
                    LJytmxx::getExaminaimcode,
                    LJytmxx::getDoctrequestno,
                    LJytmxx::getReceivetime,
                    LJytmxx::getExecutetime,
                    LJytmxx::getChecktime,
                    LJytmxx::getSampleno);
            queryWrapper.in(LJytmxx::getDoctrequestno, doctRequestNoList);
            List<LJytmxx> lJytmxxList = ilJytmxxService.list(queryWrapper);


            for (ReportReadyDocNameDTO reportReadyDocName : filterdeptcode) {
                //备注处理
                if (reportReadyDocName.getBeiZhu() != null) {
                    String newBeiZhu = new CommonMethod().RemarkExtend(reportReadyDocName.getBeiZhu());
                    reportReadyDocName.setBeiZhu(newBeiZhu);
                }
                //把骨外科1472改为1035
                if (reportReadyDocName.getDeptCode().equals("1035")) {
                    reportReadyDocName.setDeptCode("1472");
                    reportReadyDocName.setDeptName("骨科-关节外科");
                }
                //诊断号
                String clinicCode = reportReadyDocName.getClinicCode();
                //检验列表
//                List<LJysqdxx> lJysqdxxsByDorctrequestno = ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode);
                List<LJysqdxx> lJysqdxxsByDorctrequestno = new ArrayList<>();
                List<LJysqdxx> lJysqdxxListByClineCode = lJysqdxxList.stream()
                        .filter(t -> t.getPatientno().equals(clinicCode))
                        .collect(Collectors.toList());
                for (LJysqdxx lJysqdxx : lJysqdxxListByClineCode) {
                    List<LJytmxx> collect = lJytmxxList.stream()
                            .filter(t -> t.getDoctrequestno().equals(lJysqdxx.getDoctrequestno()))
                            .collect(Collectors.toList());
                    lJysqdxx.setLJysqdxxXmmxList(collect);
                    lJysqdxxsByDorctrequestno.add(lJysqdxx);
                }

                //已检查集合
                List<String> erApplyItemOutsDoIt = reportReadyDocName.getErApplyItemOutsDoIt();
                String doItNames = resultString(erApplyItemOutsDoIt);
                reportReadyDocName.setInspectName(doItNames);
                //reportReadyDocName.setErApplyItemOutsDoIt(null);
                //未检查集合
                List<String> erApplyItemOutsNotDoIt = reportReadyDocName.getErApplyItemOutsNotDoIt();
                String notDoIt = resultString(erApplyItemOutsNotDoIt);
                reportReadyDocName.setNotInspectName(notDoIt);
                //reportReadyDocName.setErApplyItemOutsNotDoIt(null);

                //获取检验完成度
                //获取单号
                List<String> doctrequestnos = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getDoctrequestno)
                        .collect(Collectors.toList());

                if (CollectionUtil.isEmpty(doctrequestnos)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }

                List<LJysqdxxXmmx> lJysqdxxXmmxsByZtId2 = lJysqdxxXmmxMapper.getLJysqdxxXmmxsByZtId2(doctrequestnos);
                //拿到ZTID编码集合
                List<LJysqdxxXmmx> lJysqdxxXmmxByDoctrequestnos = new ArrayList<>();
                for (int i = 0; i < doctrequestnos.size(); i++) {
//                    List<LJysqdxxXmmx> searchList =ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos
//                    (doctrequestnos.get(i));
                    String doctrequestno = doctrequestnos.get(i);
                    List<LJysqdxxXmmx> searchList = lJysqdxxXmmxsByZtId2.stream()
                            .filter(t -> t.getDoctrequestno().equals(doctrequestno))
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(searchList)) {
                        lJysqdxxXmmxByDoctrequestnos.addAll(searchList);
                    }
                }
                Map<String, List<String>> ljytmxxByExaminaimCode = ilJytmxxService.getLjytmxxByExaminaimCode(
                        lJysqdxxXmmxByDoctrequestnos,
                        clinicCode);

                if (CollectionUtils.isEmpty(lJysqdxxXmmxByDoctrequestnos)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }
                if (CollectionUtil.isEmpty(ljytmxxByExaminaimCode)) {
                    reportReadyDocName.setExamineProgress("0" + "/" + lJysqdxxXmmxByDoctrequestnos.size());
                } else {
                    List<String> doItList = ljytmxxByExaminaimCode.get("doIt");

                    //已经做完的检验
                    reportReadyDocName.setDoneExamine(resultString(doItList));
                    reportReadyDocName.setExamineProgress(doItList.size() + "/" + lJysqdxxXmmxByDoctrequestnos.size());
                }

                //组套名称叠加
                List<String> examinaimNames = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getExaminaim)
                        .collect(Collectors.toList());
                //懒得改结构了,在查一次吧
                ExamineSpecial examineSpecialByClinicCode = iExamineSpecialService.getExamineSpecialByClinicCode(
                        clinicCode);
                String examineName = examineSpecialByClinicCode.getExamineName() == null ? "" :
                        examineSpecialByClinicCode.getExamineName();
                boolean nullPorint = StringUtil.isNotEmpty(examineName);

                if (nullPorint) {
                    LocalDateTime executionTime = examineSpecialByClinicCode.getExecutionTime();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String executionString = "等通知。";
                    if (executionTime != null) {
                        executionString = dateTimeFormatter.format(executionTime);
                    }
                    List<String> strings = new ArrayList<>();
                    for (String examinaimName : examinaimNames) {
                        int findIndex = examinaimName.indexOf("■新冠核酸(限新开住院证患者)");
                        if (findIndex == -1) {
                            strings.add(examinaimName);
                            continue;
                        }

                        examinaimName = examinaimName.replace("■新冠核酸(限新开住院证患者)",
                                "■新冠核酸(" + executionString + ")");

                        strings.add(examinaimName);
                    }
                    examinaimNames.clear();
                    examinaimNames.addAll(strings);
                }

                String doneExamine = resultString(examinaimNames);
                reportReadyDocName.setExamineListName(doneExamine);


            }
            return reportReadyDocNames.stream()
                    .sorted(Comparator.comparing(ReportReadyDocNameDTO::getCreateTime, Comparator.reverseOrder())
                            .thenComparing(ReportReadyDocNameDTO::getDeptCode, Comparator.reverseOrder()))
                    .collect(Collectors.toList());
        } catch (Exception ex) {
            int a = 1;
        }
        return reportReadyDocNames;
    }

    @Override
    public List<ReportReadyDocNameDTO> geRJSStReportList(VYqBrdjxxConditionRequest requestInfo) {
        List<ReportReadyDocNameDTO> reportReadyDocNames = new ArrayList<>();
        try {
            List<ReportReadyDocNameDTO> filterdeptcode = new ArrayList<>();
            reportReadyDocNames = baseMapper.getRJSSReportList(requestInfo);
            if (!CollectionUtil.isEmpty(requestInfo.getDeptCodeList())) {
                filterdeptcode = reportReadyDocNames.stream()
                        .filter(t -> requestInfo.getDeptCodeList().contains(t.getDeptCode()))
                        .collect(Collectors.toList());
                if (CollectionUtil.isEmpty(filterdeptcode)) {
                    return null;
                }
            } else {
                filterdeptcode = reportReadyDocNames;
            }

            List<String> clinicCodeList = reportReadyDocNames.stream()
                    .map(ReportReadyDocNameDTO::getClinicCode)
                    .collect(Collectors.toList());
            // 获取相应的诊断号的LJysqdxx集合
            LambdaQueryWrapper<LJysqdxx> lJysqdxxQueryWrapper = new LambdaQueryWrapper<>();
            lJysqdxxQueryWrapper.in(LJysqdxx::getPatientno, clinicCodeList);
            List<LJysqdxx> lJysqdxxList = lJysqdxxMapper.selectList(lJysqdxxQueryWrapper);
            // 获取lJysqdxxList中所有的doctrequestno形成集合
            List<String> doctRequestNoList = lJysqdxxList.stream()
                    .map(LJysqdxx::getDoctrequestno)
                    .collect(Collectors.toList());
            // 获取另一个比对列表，提前放到jvm内存
            LambdaQueryWrapper<LJytmxx> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(LJytmxx::getExaminaim,
                    LJytmxx::getExaminaimcode,
                    LJytmxx::getDoctrequestno,
                    LJytmxx::getReceivetime,
                    LJytmxx::getExecutetime,
                    LJytmxx::getChecktime,
                    LJytmxx::getSampleno);
            queryWrapper.in(LJytmxx::getDoctrequestno, doctRequestNoList);
            List<LJytmxx> lJytmxxList = ilJytmxxService.list(queryWrapper);


            for (ReportReadyDocNameDTO reportReadyDocName : filterdeptcode) {
                //备注处理
                if (reportReadyDocName.getBeiZhu() != null) {
                    String newBeiZhu = new CommonMethod().RemarkExtend(reportReadyDocName.getBeiZhu());
                    reportReadyDocName.setBeiZhu(newBeiZhu);
                }
                //把骨外科1472改为1035
                if (reportReadyDocName.getDeptCode().equals("1035")) {
                    reportReadyDocName.setDeptCode("1472");
                    reportReadyDocName.setDeptName("骨科-关节外科");
                }
                //诊断号
                String clinicCode = reportReadyDocName.getClinicCode();
                //检验列表
//                List<LJysqdxx> lJysqdxxsByDorctrequestno = ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode);
                List<LJysqdxx> lJysqdxxsByDorctrequestno = new ArrayList<>();
                List<LJysqdxx> lJysqdxxListByClineCode = lJysqdxxList.stream()
                        .filter(t -> t.getPatientno().equals(clinicCode))
                        .collect(Collectors.toList());
                for (LJysqdxx lJysqdxx : lJysqdxxListByClineCode) {
                    List<LJytmxx> collect = lJytmxxList.stream()
                            .filter(t -> t.getDoctrequestno().equals(lJysqdxx.getDoctrequestno()))
                            .collect(Collectors.toList());
                    lJysqdxx.setLJysqdxxXmmxList(collect);
                    lJysqdxxsByDorctrequestno.add(lJysqdxx);
                }

                //已检查集合
                List<String> erApplyItemOutsDoIt = reportReadyDocName.getErApplyItemOutsDoIt();
                String doItNames = resultString(erApplyItemOutsDoIt);
                reportReadyDocName.setInspectName(doItNames);
                //reportReadyDocName.setErApplyItemOutsDoIt(null);
                //未检查集合
                List<String> erApplyItemOutsNotDoIt = reportReadyDocName.getErApplyItemOutsNotDoIt();
                String notDoIt = resultString(erApplyItemOutsNotDoIt);
                reportReadyDocName.setNotInspectName(notDoIt);
                //reportReadyDocName.setErApplyItemOutsNotDoIt(null);

                //获取检验完成度
                //获取单号
                List<String> doctrequestnos = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getDoctrequestno)
                        .collect(Collectors.toList());

                if (CollectionUtil.isEmpty(doctrequestnos)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }

                List<LJysqdxxXmmx> lJysqdxxXmmxsByZtId2 = lJysqdxxXmmxMapper.getLJysqdxxXmmxsByZtId2(doctrequestnos);
                //拿到ZTID编码集合
                List<LJysqdxxXmmx> lJysqdxxXmmxByDoctrequestnos = new ArrayList<>();
                for (int i = 0; i < doctrequestnos.size(); i++) {
//                    List<LJysqdxxXmmx> searchList =ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos
//                    (doctrequestnos.get(i));
                    String doctrequestno = doctrequestnos.get(i);
                    List<LJysqdxxXmmx> searchList = lJysqdxxXmmxsByZtId2.stream()
                            .filter(t -> t.getDoctrequestno().equals(doctrequestno))
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(searchList)) {
                        lJysqdxxXmmxByDoctrequestnos.addAll(searchList);
                    }
                }
                Map<String, List<String>> ljytmxxByExaminaimCode = ilJytmxxService.getLjytmxxByExaminaimCode(
                        lJysqdxxXmmxByDoctrequestnos,
                        clinicCode);

                if (CollectionUtils.isEmpty(lJysqdxxXmmxByDoctrequestnos)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }
                if (CollectionUtil.isEmpty(ljytmxxByExaminaimCode)) {
                    reportReadyDocName.setExamineProgress("0" + "/" + lJysqdxxXmmxByDoctrequestnos.size());
                } else {
                    List<String> doItList = ljytmxxByExaminaimCode.get("doIt");

                    //已经做完的检验
                    reportReadyDocName.setDoneExamine(resultString(doItList));
                    reportReadyDocName.setExamineProgress(doItList.size() + "/" + lJysqdxxXmmxByDoctrequestnos.size());
                }

                //组套名称叠加
                List<String> examinaimNames = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getExaminaim)
                        .collect(Collectors.toList());
                //懒得改结构了,在查一次吧
                ExamineSpecial examineSpecialByClinicCode = iExamineSpecialService.getExamineSpecialByClinicCode(
                        clinicCode);
                String examineName = examineSpecialByClinicCode.getExamineName() == null ? "" :
                        examineSpecialByClinicCode.getExamineName();
                boolean nullPorint = StringUtil.isNotEmpty(examineName);

                if (nullPorint) {
                    LocalDateTime executionTime = examineSpecialByClinicCode.getExecutionTime();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String executionString = "等通知。";
                    if (executionTime != null) {
                        executionString = dateTimeFormatter.format(executionTime);
                    }
                    List<String> strings = new ArrayList<>();
                    for (String examinaimName : examinaimNames) {
                        int findIndex = examinaimName.indexOf("■新冠核酸(限新开住院证患者)");
                        if (findIndex == -1) {
                            strings.add(examinaimName);
                            continue;
                        }

                        examinaimName = examinaimName.replace("■新冠核酸(限新开住院证患者)",
                                "■新冠核酸(" + executionString + ")");

                        strings.add(examinaimName);
                    }
                    examinaimNames.clear();
                    examinaimNames.addAll(strings);
                }

                String doneExamine = resultString(examinaimNames);
                reportReadyDocName.setExamineListName(doneExamine);


            }
            return reportReadyDocNames.stream()
                    .sorted(Comparator.comparing(ReportReadyDocNameDTO::getDeptCode).reversed())
                    .collect(Collectors.toList());
        } catch (Exception ex) {
            int a = 1;
        }
        return reportReadyDocNames;
    }


    @Override
    public List<ReportReadyDocNameDTO> getReportListIntegrated(String strDeptList, String jobNumber) {
        List<ReportReadyDocNameDTO> reportReadyDocNames = new ArrayList<>();
        try {
            List<String> deptList = Arrays.asList(strDeptList.split(","));
            VYqBrdjxxConditionRequest requestInfo = new VYqBrdjxxConditionRequest();
            requestInfo.setDeptCodeList(deptList);
            requestInfo.setJobNumber(jobNumber);
            List<ReportReadyDocNameDTO> filterdeptcode = new ArrayList<>();
            reportReadyDocNames = baseMapper.getReportList(requestInfo);
            //reportReadyDocNames =reportReadyDocNames.stream().filter(t->t.getName().equals("钟功元")).collect
            // (Collectors.toList());
            if (!CollectionUtil.isEmpty(requestInfo.getDeptCodeList())) {
                filterdeptcode = reportReadyDocNames.stream()
                        .filter(t -> requestInfo.getDeptCodeList().contains(t.getDeptCode()))
                        .collect(Collectors.toList());
                if (CollectionUtil.isEmpty(filterdeptcode)) {
                    return null;
                }
            } else {
                filterdeptcode = reportReadyDocNames;
            }


            for (ReportReadyDocNameDTO reportReadyDocName : filterdeptcode) {
                //备注处理
                if (reportReadyDocName.getBeiZhu() != null) {
                    String newBeiZhu = new CommonMethod().RemarkExtend(reportReadyDocName.getBeiZhu());
                    reportReadyDocName.setBeiZhu(newBeiZhu);
                }
                //把骨外科1472改为1035
                if (reportReadyDocName.getDeptCode().equals("1035")) {
                    reportReadyDocName.setDeptCode("1472");
                    reportReadyDocName.setDeptName("骨科-关节外科");
                }
                //诊断号
                String clinicCode = reportReadyDocName.getClinicCode();
                //检验列表
                List<LJysqdxx> lJysqdxxsByDorctrequestno = ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode);

                //已检查集合
                List<String> erApplyItemOutsDoIt = reportReadyDocName.getErApplyItemOutsDoIt();
                String doItNames = resultString(erApplyItemOutsDoIt);
                reportReadyDocName.setInspectName(doItNames);
                //reportReadyDocName.setErApplyItemOutsDoIt(null);
                //未检查集合
                List<String> erApplyItemOutsNotDoIt = reportReadyDocName.getErApplyItemOutsNotDoIt();
                String notDoIt = resultString(erApplyItemOutsNotDoIt);
                reportReadyDocName.setNotInspectName(notDoIt);
                //reportReadyDocName.setErApplyItemOutsNotDoIt(null);

                //获取检验完成度
                //获取单号
                List<String> doctrequestnos = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getDoctrequestno)
                        .collect(Collectors.toList());

                if (CollectionUtil.isEmpty(doctrequestnos)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }

                //拿到ZTID编码集合
                List<LJysqdxxXmmx> lJysqdxxXmmxByDoctrequestnos = new ArrayList<>();
                for (int i = 0; i < doctrequestnos.size(); i++) {
                    List<LJysqdxxXmmx> searchList =
                            ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos(doctrequestnos.get(
                            i));
                    if (CollectionUtils.isNotEmpty(searchList)) {
                        lJysqdxxXmmxByDoctrequestnos.addAll(searchList);
                    }
                }
                Map<String, List<String>> ljytmxxByExaminaimCode = ilJytmxxService.getLjytmxxByExaminaimCode(
                        lJysqdxxXmmxByDoctrequestnos,
                        clinicCode);

                if (CollectionUtil.isEmpty(ljytmxxByExaminaimCode)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }

                List<String> doItList = ljytmxxByExaminaimCode.get("doIt");

                //已经做完的检验
                reportReadyDocName.setDoneExamine(resultString(doItList));
                reportReadyDocName.setExamineProgress(doItList.size() + "/" + lJysqdxxXmmxByDoctrequestnos.size());

                //组套名称叠加
                List<String> examinaimNames = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getExaminaim)
                        .collect(Collectors.toList());
                //懒得改结构了,在查一次吧
                ExamineSpecial examineSpecialByClinicCode = iExamineSpecialService.getExamineSpecialByClinicCode(
                        clinicCode);
                String examineName = examineSpecialByClinicCode.getExamineName() == null ? "" :
                        examineSpecialByClinicCode.getExamineName();
                boolean nullPorint = StringUtil.isNotEmpty(examineName);

                if (nullPorint) {
                    LocalDateTime executionTime = examineSpecialByClinicCode.getExecutionTime();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String executionString = "等通知。";
                    if (executionTime != null) {
                        executionString = dateTimeFormatter.format(executionTime);
                    }
                    List<String> strings = new ArrayList<>();
                    for (String examinaimName : examinaimNames) {
                        int findIndex = examinaimName.indexOf("■新冠核酸(限新开住院证患者)");
                        if (findIndex == -1) {
                            strings.add(examinaimName);
                            continue;
                        }

                        examinaimName = examinaimName.replace("■新冠核酸(限新开住院证患者)",
                                "■新冠核酸(" + executionString + ")");

                        strings.add(examinaimName);
                    }
                    examinaimNames.clear();
                    examinaimNames.addAll(strings);
                }

                String doneExamine = resultString(examinaimNames);
                reportReadyDocName.setExamineListName(doneExamine);


            }
            return reportReadyDocNames.stream()
                    .sorted(Comparator.comparing(ReportReadyDocNameDTO::getDeptCode).reversed())
                    .collect(Collectors.toList());
        } catch (Exception ex) {
            int a = 1;
        }
        return reportReadyDocNames;
    }

    @Override
    public List<ReportReadyDocNameDTO> getRJSSReportListIntegrated(String strDeptList, String jobNumber) {
        List<ReportReadyDocNameDTO> reportReadyDocNames = new ArrayList<>();
        try {
            List<String> deptList = Arrays.asList(strDeptList.split(","));
            VYqBrdjxxConditionRequest requestInfo = new VYqBrdjxxConditionRequest();
            requestInfo.setDeptCodeList(deptList);
            requestInfo.setJobNumber(jobNumber);
            List<ReportReadyDocNameDTO> filterdeptcode = new ArrayList<>();
            reportReadyDocNames = baseMapper.getRJSSReportList(requestInfo);
            //reportReadyDocNames =reportReadyDocNames.stream().filter(t->t.getName().equals("钟功元")).collect
            // (Collectors.toList());
            if (!CollectionUtil.isEmpty(requestInfo.getDeptCodeList())) {
                filterdeptcode = reportReadyDocNames.stream()
                        .filter(t -> requestInfo.getDeptCodeList().contains(t.getDeptCode()))
                        .collect(Collectors.toList());
                if (CollectionUtil.isEmpty(filterdeptcode)) {
                    return null;
                }
            } else {
                filterdeptcode = reportReadyDocNames;
            }


            for (ReportReadyDocNameDTO reportReadyDocName : filterdeptcode) {
                //备注处理
                if (reportReadyDocName.getBeiZhu() != null) {
                    String newBeiZhu = new CommonMethod().RemarkExtend(reportReadyDocName.getBeiZhu());
                    reportReadyDocName.setBeiZhu(newBeiZhu);
                }
                //把骨外科1472改为1035
                if (reportReadyDocName.getDeptCode().equals("1035")) {
                    reportReadyDocName.setDeptCode("1472");
                    reportReadyDocName.setDeptName("骨科-关节外科");
                }
                //诊断号
                String clinicCode = reportReadyDocName.getClinicCode();
                //检验列表
                List<LJysqdxx> lJysqdxxsByDorctrequestno = ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode);

                //已检查集合
                List<String> erApplyItemOutsDoIt = reportReadyDocName.getErApplyItemOutsDoIt();
                String doItNames = resultString(erApplyItemOutsDoIt);
                reportReadyDocName.setInspectName(doItNames);
                //reportReadyDocName.setErApplyItemOutsDoIt(null);
                //未检查集合
                List<String> erApplyItemOutsNotDoIt = reportReadyDocName.getErApplyItemOutsNotDoIt();
                String notDoIt = resultString(erApplyItemOutsNotDoIt);
                reportReadyDocName.setNotInspectName(notDoIt);
                //reportReadyDocName.setErApplyItemOutsNotDoIt(null);

                //获取检验完成度
                //获取单号
                List<String> doctrequestnos = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getDoctrequestno)
                        .collect(Collectors.toList());

                if (CollectionUtil.isEmpty(doctrequestnos)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }

                //拿到ZTID编码集合
                List<LJysqdxxXmmx> lJysqdxxXmmxByDoctrequestnos = new ArrayList<>();
                for (int i = 0; i < doctrequestnos.size(); i++) {
                    List<LJysqdxxXmmx> searchList =
                            ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos(doctrequestnos.get(
                            i));
                    if (CollectionUtils.isNotEmpty(searchList)) {
                        lJysqdxxXmmxByDoctrequestnos.addAll(searchList);
                    }
                }
                Map<String, List<String>> ljytmxxByExaminaimCode = ilJytmxxService.getLjytmxxByExaminaimCode(
                        lJysqdxxXmmxByDoctrequestnos,
                        clinicCode);

                if (CollectionUtil.isEmpty(ljytmxxByExaminaimCode)) {
                    reportReadyDocName.setExamineProgress("0/0");
                    continue;
                }

                List<String> doItList = ljytmxxByExaminaimCode.get("doIt");

                //已经做完的检验
                reportReadyDocName.setDoneExamine(resultString(doItList));
                reportReadyDocName.setExamineProgress(doItList.size() + "/" + lJysqdxxXmmxByDoctrequestnos.size());

                //组套名称叠加
                List<String> examinaimNames = lJysqdxxsByDorctrequestno.stream()
                        .map(LJysqdxx::getExaminaim)
                        .collect(Collectors.toList());
                //懒得改结构了,在查一次吧
                ExamineSpecial examineSpecialByClinicCode = iExamineSpecialService.getExamineSpecialByClinicCode(
                        clinicCode);
                String examineName = examineSpecialByClinicCode.getExamineName() == null ? "" :
                        examineSpecialByClinicCode.getExamineName();
                boolean nullPorint = StringUtil.isNotEmpty(examineName);

                if (nullPorint) {
                    LocalDateTime executionTime = examineSpecialByClinicCode.getExecutionTime();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String executionString = "等通知。";
                    if (executionTime != null) {
                        executionString = dateTimeFormatter.format(executionTime);
                    }
                    List<String> strings = new ArrayList<>();
                    for (String examinaimName : examinaimNames) {
                        int findIndex = examinaimName.indexOf("■新冠核酸(限新开住院证患者)");
                        if (findIndex == -1) {
                            strings.add(examinaimName);
                            continue;
                        }

                        examinaimName = examinaimName.replace("■新冠核酸(限新开住院证患者)",
                                "■新冠核酸(" + executionString + ")");

                        strings.add(examinaimName);
                    }
                    examinaimNames.clear();
                    examinaimNames.addAll(strings);
                }

                String doneExamine = resultString(examinaimNames);
                reportReadyDocName.setExamineListName(doneExamine);


            }
            return reportReadyDocNames.stream()
                    .sorted(Comparator.comparing(ReportReadyDocNameDTO::getDeptCode).reversed())
                    .collect(Collectors.toList());
        } catch (Exception ex) {
            int a = 1;
        }
        return reportReadyDocNames;
    }

    /**
     * 院前准备中心报表信息--excel下载
     *
     * @author ly
     * @since 2021-09-02 17:19
     */
    @Override
    public void getReportListDownLoadExcel(VYqBrdjxxConditionRequest request) throws IOException {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        List<ReportReadyDocNameDTO> reportList = getReportList(request);
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(reportList);
        EasyExcel.write(response.getOutputStream(), ReportReadyDocNameDTO.class)
                .registerWriteHandler(new BizMergeStrategy(map))
                .sheet("sheet")
                .doWrite(reportList);
    }

    @Override
    public void getListPatientInfoToDoctorExcel(PatientInfoToDoctorDTO requestInfo) throws IOException {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        List<PatientInfoToDoctorVO> reportList = listPatientInfoToDoctor(requestInfo);
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(reportList);
        EasyExcel.write(response.getOutputStream(), PatientInfoToDoctorVO.class)
                .registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter())
                .registerWriteHandler(new BizMergeStrategy(map))
                .sheet("sheet")
                .doWrite(reportList);


    }

    @Override
    public void getReportListIntegratedDownLoadExcel(String strDeptList, String jobNumber) throws IOException {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        List<ReportReadyDocNameDTO> reportList = getReportListIntegrated(strDeptList, jobNumber);
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(reportList);
        EasyExcel.write(response.getOutputStream(), ReportReadyDocNameDTO.class)
                .registerWriteHandler(new BizMergeStrategy(map))
                .sheet("sheet")
                .doWrite(reportList);
    }

    @Override
    public void getRJSSReportListDownLoadExcel(VYqBrdjxxConditionRequest request) throws IOException {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        List<ReportReadyDocNameDTO> reportList = geRJSStReportList(request);
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(reportList);
        EasyExcel.write(response.getOutputStream(), ReportReadyDocNameDTO.class)
                .registerWriteHandler(new BizMergeStrategy(map))
                .sheet("sheet")
                .doWrite(reportList);
    }

    @Override
    public List<PatientInfoToDoctorVO> listPatientInfoToDoctor(PatientInfoToDoctorDTO requestInfo) {
        if (requestInfo.getType() != 1 || requestInfo.getType() == null) {
            String jobNumber = requestInfo.getJobNumber();
            if (StringUtils.isBlank(jobNumber)) {
                throw new RuntimeException("医生工号为null");
            }
        }
        //医惠那边传值少了个isPay，这里做判断，如果是空的，赋值2
        if (requestInfo.getIsPay() == null) {
            requestInfo.setIsPay(2);
        }
        List<PatientInfoToDoctorVO> patientInfoToDoctorVOList = null;
        List<PatientInfoToDoctorVO> parentInfoList = baseMapper.getParentInfoList(requestInfo);
        if (requestInfo.getIsPay() == 0) {
            patientInfoToDoctorVOList = parentInfoList;

        } else if (requestInfo.getIsPay() == 1) {
            patientInfoToDoctorVOList = parentInfoList.stream()
                    .filter(s -> s.getIsPay().equals("未收费"))
                    .collect(Collectors.toList());
        } else if (requestInfo.getIsPay() == 2) {
            patientInfoToDoctorVOList = parentInfoList.stream()
                    .filter(s -> s.getIsPay().equals("已收费"))
                    .collect(Collectors.toList());
        }

        return patientInfoToDoctorVOList;
    }


//    @Override
//    public PageInfo<ThisIiPrepayin> getHandworkPrepayin(HandworkPrepayinDto handworkPrepayinDto) {
//        PageHelper.startPage(handworkPrepayinDto.getPageNum(), handworkPrepayinDto.getPageSize());
//        List<ThisIiPrepayin> resultList = baseMapper.getHandworkPrepayin(handworkPrepayinDto);
//        List<String> operCodeList = resultList.stream().map(ThisIiPrepayin::getOperCode).collect(Collectors.toList());
//        if (CollectionUtils.isNotEmpty(operCodeList)){
//            List<ThisIiPrepayin> docList = baseMapper.getDoctorNameByCode(operCodeList);
//
//            resultList.stream().forEach(r->{
//                ThisIiPrepayin thisIiPrepayin = docList.stream().filter(d -> d.getOperCode().equals(r.getOperCode()
//                )).findFirst().orElse(null);
//                if (thisIiPrepayin != null){
//                    r.setDoctName(thisIiPrepayin.getDoctName());
//                } else {
//                    r.setDoctName("admin");
//                }
//            });
//        }
//
////        docList.stream().filter(d ->d.getOperCode().compareTo(r.getOperCode()) == 0).collect(Collectors.toList())
// .stream().forEach(s -> s.setDoctName(r.getDoctName()));
//
//
//        return new PageInfo<>(resultList);
//    }


    /**
     * 遍历集合将参赛全部合并起来
     *
     * @param erApplyItem 需要合拼的集合
     * @return java.lang.String
     * @author ly
     * @since 2021-08-25 15:15
     */
    private String resultString(List<String> erApplyItem) {
        if (CollectionUtil.isEmpty(erApplyItem)) {
            return null;
        }

        StringBuilder stringBuffer = new StringBuilder();
        for (String s : erApplyItem) {
            stringBuffer.append(s);
            stringBuffer.append("+");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }


    /**
     * 获取今天的0:0:0
     *
     * @return java.util.Date
     * @author ly
     * @date 2021/5/20 9:14
     */
    private static Date getLastMonthStartDay() {
        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.MONTH,7);
//        calendar.set(Calendar.DAY_OF_MONTH, 27);

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取今天的23:59:59
     *
     * @return java.util.Date
     * @author ly
     * @date 2021/5/20 9:35
     */
    private static Date getLastMonthLastDay() {
        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.MONTH,7);
//        calendar.set(Calendar.DAY_OF_MONTH, 27);

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }
}
